// 云函数入口文件
const cloud = require('wx-server-sdk')

var moment = require('moment');

cloud.init()

const db=cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  //------------------------------------------------获取生成订单编号的必要数据
  let data = JSON.parse(event.uploadData);//接受客户端上传的数据(文本格式->json格式)
  let orderNumber = data.orderId; //获取订单编号
  //获取当前日期和时间，作为订单成立的日期和时间 
  let orderDate = moment().utc().utcOffset(8).format('YYYY-MM-DD');
  let orderTime = moment().utc().utcOffset(8).format('HH:mm:ss');
  //--------------------------------------------------------------------返回数据格式
  let res={};
  res.result='fail';
  res.error='';
  //--------------------------------------------------------------------【生成订单取餐号】
  //获取当日的订单数量
  let todayOrdersCount = await db.collection('orders').where({ orderDate: orderDate }).count()
  .catch(err=>{
    return {
      result:"fail",
      error:"查询当日订单数量错误"
    }
  }) 
  let simpleId = todayOrdersCount.total + 1; //简单流水号：订单数量+1
  //--------------------------------------------------------------------【订单信息记录至orders】
  let addData={
    orderId: data.orderId, //订单号
    prepayId: data.prepayId,//统一下单ID
    userId: data.userId, //用户编号
    openId:event.userInfo.openId,//openid
    oneDayId: simpleId,
    simpleId: ('0000'+simpleId).substr(-4),//订单取餐号
    orderDate: orderDate,//订单日期
    orderTime: orderTime,//订单时间
    orderTypeId: data.orderTypeId,//订单类型ID
    orderTypeName: data.orderTypeName,//订单类型
    reserveTime: data.reserveTime,//预约时间
    address: data.address,//地址
    orderRemark: data.orderRemark,//订单备注
    totalCount: data.totalCount,//订单总数量
    totalCost: data.totalCost,//订单总金额
    deliveryCost: data.deliveryCost, //订单配送费
    extraDeliveryCost: data.extraDeliveryCost, //订单附加服务费
    payType: data.payType,//支付方式
    status: '进行中',//订单初始状态
    cartListData: data.cartListData
  }
  let addPromise = await db.collection('orders').add({ data: addData })
  if (addPromise.errMsg == "collection.add:ok")
  {
    //返回数据
    return {
      order: addData,
      result: 'success',
      error: ''
    }
  }
  else
  {
    return {
      result: 'fail',
      error: '录入订单信息失败'
    }
  }
}